package com.diandiansong.app.ui.index;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.diandiansong.app.R;
import com.diandiansong.app.entity.OrderIndexInfo;
import com.diandiansong.app.ui.base.BaseAct;
import com.diandiansong.app.ui.cart.Pay;
import com.diandiansong.app.utils.A;
import com.diandiansong.app.utils.Api;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import diandiansong.library.tabviewpager.SmartTabLayout;
import diandiansong.library.tabviewpager.utilsv4.FragmentPagerItemAdapter;
import diandiansong.library.tabviewpager.utilsv4.FragmentPagerItems;
import diandiansong.library.ui.base.FastListFragment;
import diandiansong.library.utils.BaseEntity;
import diandiansong.library.utils.CCallBack;
import diandiansong.library.utils.ImgLoader;

/**
 * 订单
 */
public class Order extends BaseAct {
    @BindView(R.id.viewpagertab)
    SmartTabLayout mViewpagertab;
    @BindView(R.id.viewpager)
    ViewPager mViewpager;

    public static void start(Context context) {
        Intent starter = new Intent(context, Order.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initTitle("我的订单");
        addContentView(R.layout.order);

        //5个子页面
        FragmentPagerItems.Creator creator = FragmentPagerItems.with(getActivity());
//        0=全部 1=待付款 2=待发货 3=待收货 4=已完成
        creator.add("全部", SubFragment.class, SubFragment.genB(0));
        creator.add("待付款", SubFragment.class, SubFragment.genB(1));
        creator.add("待发货", SubFragment.class, SubFragment.genB(2));
        creator.add("待收货", SubFragment.class, SubFragment.genB(3));
        creator.add("已完成", SubFragment.class, SubFragment.genB(4));

        FragmentPagerItems pagerItems = creator.create();

        FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(getSupportFragmentManager(), pagerItems);


        mViewpager.setAdapter(adapter);

        mViewpagertab.setViewPager(mViewpager);
    }

    public static class SubFragment extends FastListFragment {

        public static Bundle genB(int index) {
            Bundle b = new Bundle();
            b.putInt("index", index);
            return b;
        }

        int mType;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            EventBus.getDefault().register(this);
            mType = getArguments().getInt("index");
        }

        @Override
        public void onDestroy() {
            EventBus.getDefault().unregister(this);
            super.onDestroy();
        }

        @Override
        public int getItemLayoutRes() {
            return R.layout.order_item;
        }

        @Override
        public void bindItemView(int position, @NonNull View convertView) {

            final OrderIndexInfo.Data item = (OrderIndexInfo.Data) getItem(position);

            fastText(convertView, R.id.tv_order_id, "订单号：" + item.getOrderId());
            fastText(convertView, R.id.tv_date, item.getCreateTime());
            fastText(convertView, R.id.tv_pirce, "金额：￥" + item.getOrderAmount() + "    共" + item.getGoodSum() + "件商品");
            fastText(convertView, R.id.tv_status, item.getOrderStatusName());
            LinearLayout mLlGoods = findViewById(convertView, R.id.ll_goods);

            List<OrderIndexInfo.Data.Item> items = item.getItem();
            mLlGoods.removeAllViews();
            for (OrderIndexInfo.Data.Item subItem : items) {
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.order_check_good_item, null);

                ImageView mIvLogo = view.findViewById(R.id.iv_logo);
                TextView mTvName = view.findViewById(R.id.tv_name);
                TextView mTvDes = view.findViewById(R.id.tv_des);
                TextView mTvPrice = view.findViewById(R.id.tv_price);
                TextView mTvCount = view.findViewById(R.id.tv_count);

                ImgLoader.display(mIvLogo, subItem.getItemImg());
                setText(mTvName, subItem.getCommodityName());
                setText(mTvDes, subItem.getSpecInfo());
                setText(mTvPrice, "￥" + subItem.getPrice() + subItem.getUnit());
                setText(mTvCount, "x" + subItem.getNumber());

                mLlGoods.addView(view);
            }
            //0=待支付 1=待发货 2=待收货 3=已收货 4=已完成 6=取消订单
            TextView mDoCancelOrder = findViewById(convertView, R.id.do_cancel_order);
            TextView mDoConfirmReceipt = findViewById(convertView, R.id.do_confirm_receipt);
            TextView mDoPay = findViewById(convertView, R.id.do_pay);
            if (item.getOrderStatus().equals("0")) {//0=待支付 》》取消/支付
                mDoCancelOrder.setVisibility(View.VISIBLE);
                mDoPay.setVisibility(View.VISIBLE);
                mDoConfirmReceipt.setVisibility(View.GONE);

            } else if (item.getOrderStatus().equals("1")) {//1=待发货 》》无
                mDoCancelOrder.setVisibility(View.VISIBLE);
                mDoPay.setVisibility(View.GONE);
                mDoConfirmReceipt.setVisibility(View.GONE);

            } else if (item.getOrderStatus().equals("2")) {//2=待收货 》》 确认收货
                mDoCancelOrder.setVisibility(View.GONE);
                mDoPay.setVisibility(View.GONE);
                mDoConfirmReceipt.setVisibility(View.VISIBLE);

            } else {//3=已收货 4=已完成 》》无
                mDoCancelOrder.setVisibility(View.GONE);
                mDoPay.setVisibility(View.GONE);
                mDoConfirmReceipt.setVisibility(View.GONE);
            }

            //取消订单
            mDoCancelOrder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((BaseAct) getActivity()).onLoading();
                    A.orderCancel(item.getOrderId(), new CCallBack<BaseEntity>() {
                        @Override
                        public void onSuccess(BaseEntity o) throws Exception {
                            ((BaseAct) getActivity()).onLoaded();
                            onRefresh();
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            ((BaseAct) getActivity()).onLoaded();
                            toast(msg);
                        }
                    });
                }
            });
            //支付
            mDoPay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Pay.start(getActivity(), item.getOrderId());
                }
            });
            //确认收货
            mDoConfirmReceipt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((BaseAct) getActivity()).onLoading();
                    A.orderReceipt(item.getOrderId(), new CCallBack<BaseEntity>() {
                        @Override
                        public void onSuccess(BaseEntity baseEntity) throws Exception {
                            ((BaseAct) getActivity()).onLoaded();
                            onRefresh();
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            ((BaseAct) getActivity()).onLoaded();
                            toast(msg);
                        }
                    });
                }
            });
        }

        /**
         * 滑到底部时调用
         */
        @Override
        protected void loadMore() {
            A.orderIndex("" + mType, mPage, new CCallBack<OrderIndexInfo>() {
                @Override
                public void onSuccess(OrderIndexInfo o) throws Exception {
                    List<OrderIndexInfo.Data> data = o.getData();
                    if (mPage.equals("0")) {
                        mAdapter.setData(data);
                    } else {
                        mAdapter.addAll(data);
                    }
                    if (mAdapter.getDataSize() > 0) {
                        mPage = ((OrderIndexInfo.Data) getLast()).getId();
                    }
                    onLoadFinishHasMore(data.size() >= Api.PAGE_SIZE);
                }

                @Override
                public void onFailure(int code, String msg) {
                    onLoadFinishNoMore();
                    toast(msg);
                }
            });
        }

        @Override
        public void onItemClick(Object o) {
            OrderIndexInfo.Data item = (OrderIndexInfo.Data) o;
            OederDetail.start(getActivity(), item);
        }

        public static class Refresh {
        }

        public static void doRefresh() {
            EventBus.getDefault().post(new Refresh());
        }

        @Subscribe(threadMode = ThreadMode.MAIN)
        public void receiveRefresh(Refresh r) {
            onRefresh();
        }
    }
}
